package com.lzh.runke.controller.exceltest.easyexcel;

import cn.hutool.core.util.ReflectUtil;
import com.alibaba.excel.EasyExcel;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class ExportUtils {
    private ExportUtils() {
    }

    /**
     * 对list数据源将其里面的数据导入到excel表单（EasyExcel）
     *
     * @param list
     * @param filename
     * @param clazz
     * @param response
     * @param <T>
     */
    public static <T> void exportExcel(List<T> list, String filename, Class<T> clazz, HttpServletResponse response) {
        try {
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, StandardCharsets.UTF_8.name()));
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8");
            EasyExcel.write(response.getOutputStream(), clazz)
                    .sheet("sheet1")
                    .doWrite(list);
        } catch (IOException e) {
            throw new RuntimeException("导出Excel异常");
        }
    }

    /**
     * 设置序号
     *
     * @param list
     * @param <T>
     */
    public static <T> void setNumber(List<T> list) {
        int size = list.size();
        for (int i = 0; i < size; i++) {
            ReflectUtil.setFieldValue(list.get(i), "number", i + 1);
        }
    }
}
